package cn.ddiancan.xddcloud.ddccore.filter;

import cn.ddiancan.xddcloud.common.context.CloudRequestContext;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.MultiValueMap;

import java.io.IOException;
import java.util.Enumeration;

/**
 * 获取所有的外部请求头，为进行微服务间调用做准备
 */
public class LocalLoadHeaderFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(LocalLoadHeaderFilter.class);

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
        try {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            if (!CloudRequestContext.isCurrentThreadInitialized()) {
                CloudRequestContext.initializeContext();
            }
            MultiValueMap<String, String> inComing = CloudRequestContext.getContextForCurrentThread().getInComing();
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                inComing.add(headerName, request.getHeader(headerName));
            }
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            CloudRequestContext.getContextForCurrentThread().shutdown();
        }
    }
}
